package com.fastadmin.config.security.simple;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fastadmin.mapper.impl.RoleMapper;
import com.fastadmin.mapper.impl.UserMapper;
import com.fastadmin.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author YangKun
 * @date 2019/4/8 11:26.
 */
@Component
public class JwtUserDetailServiceImpl implements UserDetailsService {

    private final PasswordEncoder passwordEncoder;

    @Autowired
    UserMapper userMapper;


    @Autowired
    public JwtUserDetailServiceImpl(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUsername(username);
        if (ObjectUtil.isNull(user)) {
            return null;
        } else {
            List<Map<String, Object>> rolesNameList = userMapper.findRolesNameByUserName(username);
            ArrayList<String> roles = rolesNameList.stream().collect(ArrayList::new, (l, v) -> l.add(v.get("role_key").toString()), ArrayList::addAll);
            return new JwtUser(user.getUsername(), passwordEncoder.encode(user.getPassword()), roles.stream().toArray(String[]::new));
        }
//
//        if ("admin".equals(username)) {
//            return new JwtUser("admin", passwordEncoder.encode("123456"));
//        }
//        if ("user".equals(username)) {
//            return new JwtUser("user", passwordEncoder.encode("123456"));
//        }
//        return null;
    }
}
